﻿using blackhouse.WebNemo.Business;
using blackhouse.WebNemo.Business.Groups;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

namespace blackhouse.WebNemo.Web.Controls {
    public class LinkToEdit : HyperLink {

        #region Fields

        private Dictionary<string, string> specialParameters = new Dictionary<string, string>();
        private CultureInfo editTranslate;

        #endregion

        #region Properties

        private IGroup group;

        public string GroupSysName { get; set; }
        public int RecordId { get; set; }
        public bool OpenAsPopup { get; set; }
        public string EditTranslate {
            get {
                return (this.editTranslate == null) ? String.Empty : this.editTranslate.Name;
            }
            set {
                this.editTranslate = new CultureInfo(value);
            }
        }
        public string DisplayIdentyficatorFormat { get; set; }

        #endregion

        #region Constructors

        public LinkToEdit() {
            this.OpenAsPopup = true;
            this.RecordId = -1;
        }

        #endregion

        #region Event Handlers

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            if (!this.Visible) return;
            this.group = Factory.Instance().GetGroup(this.GroupSysName);
            NemoUrl urls = NemoUrl.Get();
            if (String.IsNullOrEmpty(this.Text))
                this.Text = "Edytuj";

            urls.GroupId = this.group.Id;
            if (this.RecordId == -1) {
                urls.View = NemoUrlView.RecordList;
                urls.RecordId = 0;
            }
            else {
                urls.View = NemoUrlView.EditRecord;
                urls.RecordId = this.RecordId;
                urls.AutoClose = this.OpenAsPopup;
            }
            if (this.editTranslate != null)
                urls.Translate = this.editTranslate; ;

            foreach (KeyValuePair<string, string> specialPrm in this.specialParameters)
                urls.AddSpecialParameter(specialPrm.Key, specialPrm.Value);


            if (this.OpenAsPopup) {
                this.Attributes.Add("data-type", "open-popup");
                NemoJsLibrary js = new NemoJsLibrary();
                js.IncludePopup(true);
            }

            if (!String.IsNullOrEmpty(this.DisplayIdentyficatorFormat))
                urls.IdentyficatorFormat = this.DisplayIdentyficatorFormat.ReplaceEx("<", "[[").ReplaceEx(">", "]]");

            this.NavigateUrl = urls.GetUrl();
        }

        public void AddSpecialParameter(string key, string value) {
            this.specialParameters[key] = value;
        }

        #endregion

    }
}